from flask import Flask, request, render_template, jsonify
import requests
from datetime import datetime
import json

app = Flask(__name__)

API_KEY = 'ds0l3i4euxtakvw42d72myocyfvnpd72'
NOW_URL = "https://eolink.o.apispace.com/456456/weather/v001/now"
HOURLY_URL = "https://eolink.o.apispace.com/456456/weather/v001/hour"  # 新增每小时预报接口
CITY_SEARCH_URL = "https://eolink.o.apispace.com/456456/function/v001/city"
HEADERS = {
    "X-APISpace-Token": API_KEY
}

def get_city_code(city_name):
    """通过城市名称搜索获取城市ID"""
    try:
        params = {"location": city_name, "items": 20, "area": "china"}
        response = requests.get(CITY_SEARCH_URL, headers=HEADERS, params=params, timeout=10)
        
        print(f"[DEBUG] 城市搜索响应: {response.text}")
        response.raise_for_status()
        data = response.json()
        
        if data.get("status") == 0:
            return data["areaList"][0]["areacode"]
    except Exception as e:
        print(f"城市搜索失败: {str(e)}")
        return None

def get_weather_data(city_code, hourly=False):
    try:
        if hourly:
            # 获取每小时预报数据
            params = {
                'areacode': city_code,
                "dataType": "json",
                "hours": 24  # 获取24小时预报
            }
            response = requests.get(HOURLY_URL, headers=HEADERS, params=params, timeout=10)
            response.raise_for_status()
            data = response.json()
            
            print("每小时预报响应:", json.dumps(data, indent=2, ensure_ascii=False))
            
            if data.get("status") == 0:
                hourly_data = []
                for hour in data.get("result", {}).get("hourly", []):
                    time_str = hour.get("time", "")
                    try:
                        time_obj = datetime.strptime(time_str, "%Y-%m-%d %H:%M")
                        time_display = time_obj.strftime("%H:%M")
                    except:
                        time_display = time_str
                    
                    hourly_data.append({
                        'time': time_display,
                        'temp': hour.get("temp", "N/A"),
                        'weather': hour.get("text", "未知"),
                        'humidity': hour.get("humidity", "N/A"),
                        'wind_speed': hour.get("wind_speed", "N/A"),
                        'wind_dir': hour.get("wind_direction", "未知")
                    })
                
                return {
                    'city': data.get("result", {}).get("location", {}).get("name", "未知城市"),
                    'hourly': hourly_data,
                    'is_hourly': True
                }
        else:
            # 获取实时天气数据
            params = {'areacode': city_code, "dataType": "json", "needIndex": "0"}
            response = requests.get(NOW_URL, headers=HEADERS, params=params, timeout=10)
            response.raise_for_status()
            data = response.json()

            if data.get("status") == 0: 
                realtime = data["result"]["realtime"]
                return {
                    'city': data["result"]["location"]["name"],
                    'temperature': realtime["temp"],
                    'description': realtime["text"],
                    'humidity': realtime["feels_like"],
                    'wind_speed': realtime["wind_speed"],
                    'detail': realtime["detail"],
                    'is_hourly': False
                }
        return None
    except Exception as e:
        print(f"天气查询失败: {str(e)}")
        if 'response' in locals():
            print("完整响应：", response.text)
        return None

@app.route("/")
def index():
    return render_template("chat.html")

@app.route("/weather", methods=['POST'])
def get_weather():
    city = request.form.get('city', '').strip()
    hourly = request.form.get('hourly', 'false') == 'true'
    
    if not city:
        return jsonify({'error': '请输入城市名字'}), 400

    city_code = get_city_code(city)
    if not city_code:
        return jsonify({'error': '城市不存在或服务暂不可用'}), 404
    
    weather_data = get_weather_data(city_code, hourly)
    if not weather_data:
        return jsonify({'error': '天气查询失败'}), 500
    return jsonify(weather_data)

if __name__ == '__main__':
    app.run(debug=True)